from PIL import Image
import os
import argparse

def gif_to_png(gif_path, output_dir):
    """Convert GIF to PNG frames"""
    # Create output directory if it doesn't exist
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # Open GIF file
    with Image.open(gif_path) as im:
        # Get base filename without extension
        base_name = os.path.splitext(os.path.basename(gif_path))[0]
        
        # Extract and save each frame
        try:
            for i in range(im.n_frames):
                # Seek to frame
                im.seek(i)
                # Convert to RGB if necessary
                rgb_im = im.convert('RGB')
                # Save as PNG
                output_path = os.path.join(output_dir, f"{base_name}_frame_{i:03d}.png")
                rgb_im.save(output_path, 'PNG')
                print(f"Saved frame {i+1}/{im.n_frames}")
        except EOFError:
            pass

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Convert GIF to PNG frames')
    parser.add_argument('gif_path', help='Path to input GIF file')
    parser.add_argument('--output', '-o', default='output_frames',
                      help='Output directory for PNG frames')
    
    args = parser.parse_args()
    gif_to_png(args.gif_path, args.output)